#!/bin/sh
#
#   Buffet service is a system daemon responsible for command dispatch and
# device state publishing on local and GCD cloud channels.
#
#   Note: Buffet is ported from ChromeOS as a binary so it expects the ChromeOS
# environment. Therefore, chroot is needed to execute buffet.
#
. /etc/utils.sh

APP="buffet"
BINARY="/bin/buffet"
FLAGS="-log_to_stderr"

running() {
  [ -n "$(pgrep -f "$BINARY")" ]
}

# Bind chroot directories to tmpfs, as chroot may exist in a read-only
# filesystem. These directories are used for the DBus socket and Buffet
# libraries.
mkdir -p "/config/buffet" # in encrypted partition
mount_once "/config/buffet" "/chroot/chromeos/var/lib/buffet"
mount_once "/tmp/run" "/chroot/chromeos/var/run"
mount_once "/etc" "/chroot/chromeos/etc"
mount_once "/tmp" "/chroot/chromeos/tmp"

# Create file for firmware version.
echo "CHROMEOS_RELEASE_VERSION=$(cat /etc/version)" > /tmp/lsb-release

# Sanity check
[ -x /chroot/chromeos/bin/buffet ] || exit 1
[ -d /chroot/chromeos/etc/buffet ] || exit 1

# Bootstrap
mkdir -p "/tmp/buffet"
cp -Rp "/etc/buffet" "/tmp"
mount_once "/tmp/buffet" "/chroot/chromeos/etc/buffet"

# Create necessary directories and dependencies to run Buffet.
mkdir -p /chroot/chromeos/var/run/buffet
mkdir -p /chroot/chromeos/etc/ssl/certs

start() {
  if running; then
    echo "Buffet is already running!"
  else
    echo "Starting buffet service..."
    (
      # Bootstrap
      wait-until-created /chroot/chromeos/etc/buffet/buffet.conf
      # Sanity check: DBus socket has to be present.
      wait-until-created /chroot/chromeos/var/run/dbus/system_bus_socket
      babysit_start 10 "$APP" "chroot /chroot/chromeos $BINARY" "$FLAGS"
      if [ ! -n "$(pgrep -f buffet_monitor)" ]; then
        buffet_monitor 7200 &
      fi
    ) &
  fi
}

stop() {
  echo "Stopping buffet..."
  pkill -x buffet$
  [ $? -ne 0 ] && echo "Failed to stop buffet..." && exit 1
  pkill -x buffet_monitor
  echo "Buffet stopped successfully"
}

restart() {
  stop
  start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
